/**
 * 版权所有(C) COVISINT 2015-2025
 * Copyright 2015-2025 COVISINT
 * 创建日期：Jun 28, 20175:41:29 PM
 * 创建人：yyang
 */
package com.wechat.framework.interceptor;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class OAuth2Interceptor extends HandlerInterceptorAdapter {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	//排除列表
	private List<String> excludes;
	
	//包含列表
	private List<String> includes;
	
	private PathMatcher pathMatcher = new AntPathMatcher();
	
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		if (getExcludes() != null) {
			if (contains(request.getRequestURI(), getExcludes())) {
				return true;
			}
		}
		if (getIncludes() != null) {
			if (!contains(request.getRequestURI(), getIncludes())) {
				return true;
			}
		}

		return preHandleLogic(request, response, handler);
	}

	public boolean preHandleLogic(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		HttpSession session = request.getSession();
		logger.info("SESSION ID IS = " + session.getId());

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		OAuthRequired annotation = method.getAnnotation(OAuthRequired.class);
		if (annotation != null) {
			Object userId = session.getAttribute("UserId");
			logger.info("UserId = " + userId);
			
			// 用户ID为空
			if (userId == null) {
				String resultUrl = request.getRequestURL().toString().replace("http://", "https://");
				logger.info("resultUrl 1 = " + resultUrl);

				String param = request.getQueryString();
				if (param != null) {
					resultUrl += "?" + param;
				}
				resultUrl = resultUrl.replace("http://", "https://");
				logger.info("resultUrl 2 = " + resultUrl);
				
				try {
					resultUrl = java.net.URLEncoder.encode(resultUrl, "utf-8").replace("http://", "https://");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				// 请求的路径
				String contextPath = request.getContextPath();
				logger.info("contextPath = " + contextPath);
				
				// System.out.println(DateUtils.getCurrentSytemTimeForString() +
				// " OAuth2 Redirect Status...1");
				// 跳转OAuth2验证
				response.sendRedirect(contextPath + "/oauth2Controller/oauth2API?resultUrl=" + resultUrl);
				return false;
			} else {
				// System.out.println(DateUtils.getCurrentSytemTimeForString() +
				// " OAuth2 NOT Redirect Status...2");
			}
		}
		return true;
	}

	private boolean contains(String requestURI, List<String> patterns) {
		for (String pattern : patterns) {
			if (pathMatcher.match(pattern, requestURI)){
				return true;
			}
		}
		return false;
	}
	
	public List<String> getExcludes() {
		return excludes;
	}
	
	public void setExcludes(List<String> excludes) {
		this.excludes = excludes;
	}
	
	public List<String> getIncludes() {
		return includes;
	}
	
	public void setIncludes(List<String> includes) {
		this.includes = includes;
	}
}
